package com.vf.cloud.paas.app.agent.common.server.signalling.pool;

import com.jfinal.kit.StrKit;
import com.vf.cloud.paas.common.cirrus.Cirrus;
import com.vf.cloud.paas.common.service.impl.RedisImpl;
import com.vf.cloud.paas.common.util.SpringContextHolder;

import io.netty.channel.ChannelHandlerContext;

public class PlayerPool {

	public static void put(String token, ChannelHandlerContext ctx) {
		Cirrus.Concurrent_Player.put(token, ctx);
		SpringContextHolder.getBean(RedisImpl.class).add(ctx.channel().id().asLongText(), token);
	}

	public static void removeByChannelId(String channelId) {
		if (SpringContextHolder.getBean(RedisImpl.class).hasKey(channelId)) {
			String token = SpringContextHolder.getBean(RedisImpl.class).get(channelId);
			if (!StrKit.isBlank(token) && Cirrus.Concurrent_Player.containsKey(token)) {
				ChannelHandlerContext ctx = Cirrus.Concurrent_Player.get(token);
				if (ctx != null)
					ctx.close();
				Cirrus.Concurrent_Player.remove(token);
			}
			SpringContextHolder.getBean(RedisImpl.class).delete(channelId);
		}
	}

	public static void removeByToken(String token) {
		if (Cirrus.Concurrent_Player.containsKey(token)) {
			ChannelHandlerContext ctx = Cirrus.Concurrent_Player.get(token);
			if (ctx != null) {
				SpringContextHolder.getBean(RedisImpl.class).delete(ctx.channel().id().asLongText());
			}
			ctx.close();
			Cirrus.Concurrent_Player.remove(token);
		}
	}

	public static ChannelHandlerContext getByToken(String token) {
		if (Cirrus.Concurrent_Player.containsKey(token)) {
			return Cirrus.Concurrent_Player.get(token);
		}
		return null;
	}

	public static boolean containsToken(String token) {
		return Cirrus.Concurrent_Player.containsKey(token);
	}

	public static String getTokenByChannelId(String ChannelId) {
		if (SpringContextHolder.getBean(RedisImpl.class).hasKey(ChannelId)) {
			return SpringContextHolder.getBean(RedisImpl.class).get(ChannelId);
		}
		return "";
	}

}
